

module.exports = (required = true) => {
    return async (ctx, next) => {
        const { authorization } = ctx.headers
        if (!authorization) {
            if (required) {
                ctx.throw(401, '没有token信息')
            } else {
                await next()
                return
            }
            return
        }
        const token = authorization.split(' ')[1]
        if (token) { 
            try {
                const userinfo = await ctx.helper.verifyJwt(token)
                ctx.userinfo = userinfo.user
                await next()
            } catch (err) {
                console.log('err',err)
                ctx.throw(401, err)
            }
        } else {
            if (required) {
                ctx.throw(401, '没有token信息')
            } else {
                await next()
            }
        }
    }
}